package com.ktjy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ktjy.dto.UserDTO;
import com.ktjy.mapper.SysUserPostMapper;
import com.ktjy.mapper.SysUserRoleMapper;
import com.ktjy.pojo.SysDept;
import com.ktjy.pojo.SysUser;
import com.ktjy.mapper.SysUserMapper;
import com.ktjy.pojo.SysUserPost;
import com.ktjy.pojo.SysUserRole;
import com.ktjy.service.ISysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author jjx
 * @since 2025-07-28
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {
    @Resource
    SysUserMapper sysUserMapper;
    @Resource
    SysUserRoleMapper sysUserRoleMapper;
    @Resource
    SysUserPostMapper sysUserPostMapper;

    @Override
    public SysUser login(String userName, String password) {
        QueryWrapper qw=new QueryWrapper();
        qw.eq("user_name",userName);
        SysUser sysUser = sysUserMapper.selectOne(qw);
        if(sysUser!=null){
            if(sysUser.getPassword().equals(password)){
                return sysUser;
            }
        }
        return null;
    }

    @Override
    public IPage<SysUser> findPage(UserDTO userDTO,
                                   Integer pageNo, Integer pageSize) {
        //构造分页条件
        Page page=new Page(pageNo,pageSize);
        return sysUserMapper.selectPage(page,userDTO);
    }

    @Override
    public boolean checkNameUnique(String name) {
        //查询数据
        QueryWrapper<SysUser> qw=new QueryWrapper<>();
        qw.eq("user_name",name);
        return count(qw)>0;
    }


    @Override
    public void saveOrUpdateUser(SysUser sysUser) {
        Long userId=sysUser.getUserId();
        //保存用户信息
        this.saveOrUpdate(sysUser);

        if(userId!=null){//说明是修改
            //先删除用户对应的角色
            QueryWrapper roleQw=new QueryWrapper();
            roleQw.eq("user_id",sysUser.getUserId());
            sysUserRoleMapper.delete(roleQw);
        }
        //批量新增用户对应角色信息
        batchInsertUserRole(sysUser.getRoleIds(), sysUser.getUserId());
        if(userId!=null){//说明是修改
            //先删除用户对应的角色
            QueryWrapper postQw=new QueryWrapper();
            postQw.eq("user_id",sysUser.getUserId());
            sysUserPostMapper.delete(postQw);
        }
        //批量新增用户对应岗位信息
        batchInsertUserPost(sysUser.getPostIds(), sysUser.getUserId());
    }

    @Override
    public SysUser findUser(Long userId) {
        //1.查询用户信息
        SysUser sysUser = this.getById(userId);

        //2.查询用户关联的岗位信息
        QueryWrapper<SysUserPost> postQw=new QueryWrapper<SysUserPost>();
        postQw.eq("user_id",sysUser.getUserId());
        List<SysUserPost> sysUserPosts = sysUserPostMapper.selectList(postQw);

        List<Long> postList = new ArrayList<Long>();
        for (SysUserPost sysUserPost : sysUserPosts) {
            postList.add(sysUserPost.getPostId());
        }
        sysUser.setPostIds(postList.toArray(new Long[0]));
        //3.查询用户关联的角色信息
        QueryWrapper<SysUserRole> roleQw=new QueryWrapper<SysUserRole>();
        roleQw.eq("user_id",sysUser.getUserId());
        List<SysUserRole> sysUserRoles = sysUserRoleMapper.selectList(roleQw);

        List<Long> roleList = new ArrayList<Long>();
        for (SysUserRole sysUserrole : sysUserRoles) {
            roleList.add(sysUserrole.getRoleId());
        }
        sysUser.setRoleIds(roleList.toArray(new Long[0]));

        return sysUser;
    }

    @Override
    public void deleteUser(Long userId) {
        //1.删除用户对应的角色信息
        QueryWrapper<SysUserRole> roleQw=new QueryWrapper<SysUserRole>();
        roleQw.eq("user_id",userId);
        sysUserRoleMapper.delete(roleQw);
        //2.删除用户对应的岗位信息
        QueryWrapper<SysUserPost> postQw=new QueryWrapper<SysUserPost>();
        postQw.eq("user_id",userId);
        sysUserPostMapper.delete(postQw);
        //3.删除用户信息
        this.removeById(userId);
    }

    /**
     * 批量新增用户对应的角色
     * @param roles
     * @param userId
     */
    private void batchInsertUserRole(Long[] roles,Long userId){
        if (roles!=null && roles.length>0) {
            List<SysUserRole> list = new ArrayList<SysUserRole>();
            for (Long roleId : roles) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }
            if (list.size() > 0) {
                sysUserRoleMapper.insert(list);
            }
        }
    }

    /**
     * 批量新增用户对应的岗位
     * @param postIds
     * @param userId
     */
    private void batchInsertUserPost(Long[] postIds,Long userId){
        if (postIds!=null && postIds.length>0) {
            List<SysUserPost> list = new ArrayList<SysUserPost>();
            for (Long postId : postIds) {
                SysUserPost up = new SysUserPost();
                up.setUserId(userId);
                up.setPostId(postId);
                list.add(up);
            }
            if (list.size() > 0) {
                sysUserPostMapper.insert(list);
            }
        }
    }
}
